package com.delayqueue.core.netty.handler.master;

import com.delayqueue.common.netty.Node;
import com.delayqueue.common.netty.handler.*;
import com.delayqueue.core.cache.NodeCacheFactory;
import com.delayqueue.core.netty.config.NettyConfig;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class MasterConnectBootstrap {

    @Autowired
    private MasterConnectHandler masterConnectHandler;

    @Autowired
    private MasterMessageHandler masterMessageHandler;

    public void connect(String ip, int port) {
        log.info("正在连接master：{}:{}", ip, port);
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(NettyConfig.worker);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                pipeline.addLast(new StringToByteEncoder());
                pipeline.addLast(new MessageToStringEncoder());

                pipeline.addLast(masterConnectHandler);
                pipeline.addLast(new ByteToStringDecoder());
                pipeline.addLast(new StringToMessageHandler());
                pipeline.addLast(masterMessageHandler);

                pipeline.addLast(new ExceptionHandler());

            }
        });
        ChannelFuture future = bootstrap.connect(ip, port);
        future.addListener((ChannelFutureListener) channelFuture -> {
            if (channelFuture.isSuccess()) {
                log.info("连接master成功！");
            } else {
                channelFuture.channel().eventLoop().schedule(() -> connect(), 1, TimeUnit.SECONDS);
            }
        });
    }

    public void connect() {
        Node node = NodeCacheFactory.master.chooseNode();
        if (node != null) {
            connect(node.getIp(), node.getPort());
        } else {
            log.info("暂无master节点");
            NettyConfig.worker.schedule((Runnable) this::connect, 1, TimeUnit.SECONDS);
        }
    }
}
